package org.jiucheng.magpiebridge.server.aio.proxy;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import org.jiucheng.magpiebridge.server.aio.ServerAttachment;

/**
 * 代理连接附件
 * 
 * @author jiucheng
 *
 */
public class ProxyAttachment {
    // 当前在写
    public final AtomicBoolean writed = new AtomicBoolean(false);
    // 代理连接
    private AsynchronousSocketChannel asynchronousSocketChannel;
    // 待写入数据
    private ByteBuffer readBuffer;
    // 待写入数据
    private ByteBuffer writeBuffer;
    // Client附件
    private ServerAttachment serverAttachment;
    private int uri;
    
    public ProxyAttachment(AsynchronousSocketChannel asynchronousSocketChannel) {
        this.asynchronousSocketChannel = asynchronousSocketChannel;
    }
    
    public AsynchronousSocketChannel getAsynchronousSocketChannel() {
        return asynchronousSocketChannel;
    }
    
    public int getUri() {
		return uri;
	}
    
    public ProxyAttachment setUri(int uri) {
		this.uri = uri;
		return this;
	}
    
    public ByteBuffer getReadBuffer() {
		return readBuffer;
	}
    
    public ProxyAttachment setReadBuffer(ByteBuffer readBuffer) {
		this.readBuffer = readBuffer;
		return this;
	}
    
    public ByteBuffer getWriteBuffer() {
        return writeBuffer;
    }
    
    public ProxyAttachment setWriteBuffer(ByteBuffer writeBuffer) {
        this.writeBuffer = writeBuffer;
        return this;
    }
    
    public ServerAttachment getServerAttachment() {
        return serverAttachment;
    }
    
    public ProxyAttachment setServerAttachment(ServerAttachment serverAttachment) {
        this.serverAttachment = serverAttachment;
        return this;
    }
    
	public boolean canWrited() {
        while (!writed.compareAndSet(false, true)) {
        	try {
				TimeUnit.MILLISECONDS.sleep(50L);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        }
        return true;
	}
	
	public void close() {
		ServerAttachment.proxys.remove(uri);
		AsynchronousSocketChannel proxy = getAsynchronousSocketChannel();
		if (proxy != null) {
			try {
				proxy.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
